package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：daqiang
 * @date ：Created in 2019/11/22
 * @description ：
 * @version: 1.0
 */

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    /**
     * 步骤：
     *  1.循环
     *  2.判断该日期是否进行了预约设置
     *      1.如果设置了，执行修改操作
     *      注意：修改时需要判断已预约人数（数据库）是否大于可预约人数（参数中）
     *      2.如果没有设置，执行添加操作
     * @param orderSettingList
     */

    @Override
    @Transactional
    public void addOrderSettings(List<OrderSetting> orderSettingList) {
        if (orderSettingList != null && orderSettingList.size() > 0){
            //循环
            for (OrderSetting orderSetting : orderSettingList) {
                //2.判断该日期是否进行了预约设置
                OrderSetting orderSettingDb = orderSettingDao.findByDate(orderSetting.getOrderDate());
                //如果设置了，执行修改操作
                if (orderSettingDb != null){
                    //注意：修改时需要判断已预约人数（数据库）是否大于可预约人数（参数中）
                    if (orderSettingDb.getReservations()>orderSetting.getNumber()){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                        throw new RuntimeException("您设置的"+sdf.format(orderSetting.getOrderDate())+"已预约人数大于可预约，不能设置！！！");
                    }else {
                        orderSettingDao.edit(orderSetting);
                    }
                }else {
                    //如果没有设置，执行添加操作
                    orderSettingDao.add(orderSetting);
                }
            }
        }

    }

    @Override
    public List<OrderSetting> findByMonth(String month) {
        String startDate =month+ "-01";
        String endDate =month+ "-31";
        Map<String,Object> map = new HashMap<>();
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        return orderSettingDao.findByMonth(map);
    }
}
